package com.xjh.serverinspect.security.handler;

import com.xjh.serverinspect.security.JwtHolder;
import com.xjh.serverinspect.security.TokenValidateException;
import com.xjh.serverinspect.security.config.SecurityConfig;
import com.xjh.serverinspect.security.service.UserDetailServiceImpl;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;

/**
 * <p>
 *
 * </p>
 *
 * @author xujinghui
 * @since 2024-12-12
 */
public class JwtAuthenticationFilter extends BasicAuthenticationFilter {

    @Value("${server.servlet.context-path:}")
    private String contextPath;

    @Resource
    private JwtHolder jwtHolder;

    @Resource
    UserDetailServiceImpl userDetailService;

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse resp, FilterChain chain) throws IOException, ServletException {
        String accessToken = req.getHeader("Authorization");
        String url = req.getRequestURI();

        boolean isWhiteUrl = Arrays.stream(SecurityConfig.getURLWhiteList()).anyMatch(u -> url.startsWith(contextPath + u));

        // 这里如果没有access_token，继续往后走，因为后面还有鉴权管理器等去判断是否拥有身份凭证，所以是可以放行的
        // 没有access_token相当于匿名访问，若有一些接口是需要权限的，则不能访问这些接口
        if (isWhiteUrl || StringUtils.isEmpty(accessToken)) {
            chain.doFilter(req, resp);
            return;
        }

        Map<String, Object> claims = jwtHolder.parseToken(accessToken);
        if (!(Boolean) claims.get("success")) {
            throw new TokenValidateException((String) claims.get("message"));
        }

        String username = (String) ((Claims) claims.get("payload")).get("username");

        // 构建UsernamePasswordAuthenticationToken,这里密码为null，是因为提供了正确的access_token,实现自动登录
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userDetailService.loadUserByUsername(username), null, AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"));
        SecurityContextHolder.getContext().setAuthentication(token);

        chain.doFilter(req, resp);
    }
}
